package com.linwen.excise.base;

import org.junit.Test;

/**
 * @author : linwen
 * @date : 上午12:26 2021/3/2
 */
public class 最大公共子串 {
    /**
     * 循环获取最大公共子串
     * @param str1
     * @param str2
     * @return
     */
    public String getMaxSubString(String str1,String str2){
        //找出长字符串
        String maxString = str1.length()>=str2.length()?str1:str2;
        String minString = maxString.equals(str1)==true?str2:str1;
        //循环次数
        int loopCount = minString.length();
        for (int i = 0; i < loopCount; i++) {
            for (int x=0,y=loopCount-i;y<=loopCount;x++,y++){
                String temp = minString.substring(x,y);
                if(maxString.contains(temp)){
                    return temp;
                }
            }
        }
        return null;
    }
    @Test
    public void test(){
        String str1 = "printhelloworld";
        String str2 = "thisishellotest";
        String maxSubString = getMaxSubString(str1, str2);
        System.out.println(maxSubString);
        String maxSubString1 = getMaxSubString1(str1, str2);
        System.out.println(maxSubString1);
    }

    public String getMaxSubString1(String str1,String str2){
        String maxString;
        String minString;
        if(str1.length()>str2.length()){
            maxString = str1;
            minString = str2;
        }else {
            maxString = str2;
            minString = str1;
        }
        int ml = minString.length();
        // 滑动窗口
        for (int i = 0; i < ml; i++) {
            for (int j = 0,k = ml-i;k<=ml; j++,k++) {
                String temp = minString.substring(j,k);
                if(maxString.contains(temp)){
                    return temp;
                }
            }

        }
        return null;

    }
}
